import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Button, Dialog, Stepper } from 'antd-mobile';
import { Badge, Popup } from 'antd-mobile';
import { ShopbagOutline } from 'antd-mobile-icons';
import Header from './Header';
import './App.css';
import { useThrottleFn } from 'ahooks';
import { Tabs, SideBar } from 'antd-mobile';

const items = [
    {
        key: '1', title: '精选套餐', text: [
            { id: '1-1', name: '皮蛋瘦肉粥套餐', img: 'http://fuss10.elemecdn.com/6/72/cb844f0bb60c502c6d5c05e0bddf5jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售12份 好评率100%', price: 31 },
        ]
    },
    {
        key: '2', title: '果拼果汁', text: [
            { id: '2-1', name: '蜜瓜圣女果', img: 'http://fuss10.elemecdn.com/e/c6/f348e811772016ae24e968238bcbfjpeg.jpeg?imageView2/1/w/114/h/114', des: '月售1份 好评率%', price: 6 },
        ]
    },
    {
        key: '3', title: '小吃主食', text: [
            { id: '3-1', name: '扁豆焖面', img: 'http://fuss10.elemecdn.com/c/6b/29e3d29b0db63d36f7c500bca31d8jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售10份 好评率98%', price: 12 },
            { id: '3-2', name: '葱花饼', img: 'http://fuss10.elemecdn.com/f/28/a51e7b18751bcdf871648a23fd3b4jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售18份 好评率100%', price: 8 },
            { id: '3-3', name: '牛肉馅饼', img: 'http://fuss10.elemecdn.com/d/b9/bcab0e8ad97758e65ae5a62b2664ejpeg.jpeg?imageView2/1/w/114/h/114', des: '月售5份 好评率99%', price: 10 },


        ]
    },
    {
        key: '4', title: '特色粥品', text: [
            { id: '4-1', name: '红豆薏米粥', img: 'http://fuss10.elemecdn.com/d/22/260bd78ee6ac6051136c5447fe307jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售156份 好评率100%', price: 4 },
            { id: '4-2', name: '皮蛋瘦肉粥', img: 'http://fuss10.elemecdn.com/c/cd/c12745ed8a5171e13b427dbc39401jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售133份 好评率100%', price: 6 },
            { id: '4-3', name: '小米南瓜粥', img: 'http://fuss10.elemecdn.com/8/a6/453f65f16b1391942af11511b7a90jpeg.jpeg?imageView2/1/w/114/h/114', des: '月售58份 好评率100%', price: 3 },
        ]
    },
    {
        key: '5', title: '爽口凉菜', text: [
            { id: '5-1', name: '香脆芥末花菜', img: 'http://fuss10.elemecdn.com/9/c6/f3bc84468820121112e79583c24efjpeg.jpeg?imageView2/1/w/114/h/114', des: '月售10份 好评率100%', price: 8 },
            { id: '5-2', name: '爽口咸菜', img: 'http://fuss10.elemecdn.com/9/b5/469d8854f9a3a03797933fd01398bjpeg.jpeg?imageView2/1/w/114/h/114', des: '月售10份 好评率100%', price: 7 },

        ]
    },
    {
        key: '6', title: '精选热菜', text: [

            { id: '6-1', name: '娃娃菜炖豆腐', img: 'http://fuss10.elemecdn.com/d/2d/b1eb45b305635d9dd04ddf157165fjpeg.jpeg?imageView2/1/w/114/h/114', des: '月售24份 好评率100%', price: 28 },
        ]
    },
    {
        key: '7', title: '冰爽饮品限时特惠', text: [
            { id: '7-1', name: 'VC无限橙果汁', img: 'http://fuss10.elemecdn.com/e/c6/f348e811772016ae24e968238bcbfjpeg.jpeg?imageView2/1/w/114/h/114', des: '月售9份 好评率100%', price: 6 },
        ]
    },
];

export default function Main() {
    const [visible1, setVisible1] = useState(false);
    const [cart, setCart] = useState(JSON.parse(localStorage.getItem('cart')) || []);
    const [activeKey, setActiveKey] = useState('1');

    // 使用 useMemo 计算购物车中的商品数量和总价，只有 cart 发生变化时才重新计算
    const cartCount = useMemo(() => cart.reduce((sum, item) => sum + item.quantity, 0), [cart]);
    const totalPrice = useMemo(() => cart.reduce((sum, item) => sum + item.quantity * item.price, 0), [cart]);

    // 处理滚动事件的逻辑（保持不变）
    const { run: handleScroll } = useThrottleFn(() => {
        let currentKey = items[0].key;
        for (const item of items) {
            const element = document.getElementById(`anchor-${item.key}`);
            if (!element) continue;
            const rect = element.getBoundingClientRect();
            if (rect.top <= 120) {
                currentKey = item.key;
            } else {
                break;
            }
        }
        setActiveKey(currentKey);
    }, { leading: true, trailing: true, wait: 100 });

    const mainElementRef = useRef(null);
    useEffect(() => {
        const mainElement = mainElementRef.current;
        if (!mainElement) return;
        mainElement.addEventListener('scroll', handleScroll);
        return () => {
            mainElement.removeEventListener('scroll', handleScroll);
        };
    }, []);

    // 更新购物车
    const updateCart = (product, quantity) => {
        const updatedCart = [...cart];
        const cartItemIndex = updatedCart.findIndex(item => item.id === product.id);

        if (cartItemIndex !== -1) {
            if (quantity > 0) {
                updatedCart[cartItemIndex].quantity = quantity;
            } else {
                updatedCart.splice(cartItemIndex, 1); // 删除数量为0的商品
            }
        } else if (quantity > 0) {
            updatedCart.push({ ...product, quantity });
        }

        setCart(updatedCart);
        localStorage.setItem('cart', JSON.stringify(updatedCart));
    };
    const isdeletCart = ()=>{
        Dialog.confirm({
            content:"确定要清空购物车吗？",
            onConfirm:()=>{
                setCart([])
                localStorage.setItem('cart', JSON.stringify([]));
            }
        })
    }
    return (
        <div style={{ position: 'relative' }} id="main">
            <Header />
            <div className="container">
                <div className="side">
                    <SideBar
                        activeKey={activeKey}
                        onChange={key => {
                            setActiveKey(key);
                            const target = document.getElementById(`anchor-${key}`);
                            if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }}
                    >
                        {items.map(item => (
                            <SideBar.Item key={item.key} title={item.title} />
                        ))}
                    </SideBar>
                </div>
                <div className="main" ref={mainElementRef}>
                    {items.map(item => (
                        <div key={item.key}>
                            <h2 id={`anchor-${item.key}`}>{item.title}</h2>
                            {item.text.map(product => {
                                const cartItem = cart.find(cartItem => cartItem.id === product.id) || {};
                                const quantity = cartItem.quantity || 0;

                                return (
                                    <div key={product.id} className="product-item">
                                        <div>
                                            <img src={product.img} height={80} width={80} />
                                        </div>
                                        <div style={{ marginLeft: '10px' }}>
                                            <h3>{product.name}</h3>
                                            <p>{product.des}</p>
                                            <p style={{ color: 'red' }}>
                                                ￥{product.price}
                                                <span style={{ display: 'inline-block', marginLeft: '30px' }}>
                                                    <Stepper
                                                        style={{ width: '80px', height: '20px' }}
                                                        value={quantity}
                                                        min={0}
                                                        onChange={value => updateCart(product, value)}
                                                    />
                                                </span>
                                            </p>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ))}
                </div>
            </div>

            {/* 购物车 */}
            <div className="car">
                <Badge content={cartCount} style={{ '--right': '15%' }}>
                    <div className="car-icon">
                        <ShopbagOutline
                            fontSize={36}
                            onClick={() => setVisible1(true)}
                        />
                    </div>
                </Badge>
                <div className="car-price">￥{totalPrice.toFixed(2)}</div>
                <div className="car-content">另需配送费￥4元</div>
                <button disabled={cart.length == 0} className="car-btn" onClick={() => {
                    console.log(cart.length);
                }}>结算</button>
            </div>

            {/* 弹出层展示购物车 */}
            <Popup
                getContainer={() => document.getElementById('main')}
                style={{ position: 'absolute', bottom: '61px', left: '0px', right: '0px' }}
                visible={visible1}
                onMaskClick={() => setVisible1(false)}
                onClose={() => setVisible1(false)}
                bodyStyle={{ height: '40vh' }}
            >
                <div>
                    {cart.length === 0 ? (
                        <h2>购物车为空</h2>
                    ) : (
                        <div>
                            <Button  onClick={isdeletCart}>清空购物车</Button>
                            {cart.map(item => (
                                <div key={item.id} className="product-item">
                                    <div>
                                        <img src={item.img} height={60} width={60} />
                                    </div>
                                    <div style={{ marginLeft: '10px' }}>
                                        <h3>{item.name}</h3>
                                        <p style={{ color: 'red' }}>￥{item.price}</p>
                                        <Stepper
                                            style={{ width: '80px', height: '20px' }}
                                            value={item.quantity}
                                            min={0}
                                            onChange={value => updateCart(item, value)}
                                        />
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </Popup>
        </div>
    );
}
